package com.user.dao;

import com.user.entity.User;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import java.util.List;

@Repository
public class UserDaoImpl implements UserDao{

    @Autowired
    private SessionFactory sessionFactory;


    //增加用户
    @Override
    public void addUser(User user) {
        sessionFactory.getCurrentSession().save(user);
    }

    //删除用户
    @Override
    public void deleteUser(int id) {
        User user= sessionFactory.getCurrentSession().load(User.class,id);
        sessionFactory.getCurrentSession().delete(user);
    }

    //按号查找用户
    @Override
    public User loadUser(int uid) {
        User user= sessionFactory.getCurrentSession().get(User.class,uid);
        return user;
    }

    @Override
    public User loadUser(String uname) {
        User user= (User) sessionFactory.getCurrentSession().createQuery("from User where name=?")
                                        .setParameter(0,uname).uniqueResult();
        return user;
    }


    //更新修改用户
    @Override
    public void update(User user) {
        sessionFactory.getCurrentSession().update(user);
    }

    //查找所有用户
    @Override
    public List<User> list() {
        List<User> users= sessionFactory.getCurrentSession().createQuery("from User")
                                        .list();
        return users;
    }

    //用户登录
    @Override
    public User login(String uname, String uPwd) {
        User user=null;
        Object o=null;
        o=sessionFactory.getCurrentSession().createQuery("from User where name=?")
                                            .setParameter(0,uname)
                                            .uniqueResult();
        if(o==null){
            return user;
        }
        if(((User) o).getName().equals(uname)&&((User) o).getPassword().equals(uPwd)){
            user=(User) o;
        }
        return user;
    }

    //是否存在用户
    @Override
    public boolean isExist(String name) {
        Object o=null;
        o=sessionFactory.getCurrentSession().createQuery("from User where name=?")
                                            .setParameter(0,name)
                                            .uniqueResult();
        if(o!=null){
            System.out.println("cunzai ");
            return true;
        }else{
            System.out.println("bucunzai");
            return false;
        }
    }
}
